﻿using IPC.DbMapper;
using IPC.DbMapper.IPCDBConnect;
using IPC.LogCommon.DelegateAndEvent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPC.WinForm.Bussiness
{
    public class ConfigDbBussiness
    {
        #region 单例模式
        private static ConfigDbBussiness _instance;
        public static ConfigDbBussiness Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ConfigDbBussiness();
                }
                return _instance;
            }
        }
        #endregion

        #region 增加或修改本机配置
        public void UpdateConfig(string configKey, string configValue)
        {
            try
            {
                IPCDbContext iPCDbContext = new IPCDbContext();
                List<SystemConfig> systemConfigs = iPCDbContext.SystemConfigs.Where(o=>o.ConfigKey == configKey).ToList();
                if (systemConfigs.Count > 0)
                {
                    foreach (SystemConfig systemConfig in systemConfigs)
                    {
                        systemConfig.ConfigValue = configValue;
                    }
                }
                else
                {
                    iPCDbContext.SystemConfigs.Add(new SystemConfig() {ConfigKey=configKey,ConfigValue=configValue });
                    //iPCDbContext.SystemConfigs.Add(new SystemConfig() { ConfigKey = configKey, ConfigValue = configValue });
                }
                iPCDbContext.SaveChangesAsync();
                iPCDbContext.Dispose();
            }
            catch (Exception ex)
            {
                DelegateAndEvent.Instance.AddAlarmInfo($"添加系统配置{configKey}失败 {ex.Message}");
            }
        }
        #endregion

        #region 获取配置
        public string GetConfigByKey(string configKey, string defaultValue="")
        {
            try
            {
                IPCDbContext iPCDbContext = new IPCDbContext();
                List<SystemConfig> systemConfigs = iPCDbContext.SystemConfigs.Where(o => o.ConfigKey == configKey).ToList();
                if (systemConfigs.Count > 0)
                {
                    iPCDbContext.Dispose();
                    return systemConfigs[0].ConfigValue;
                }
                return defaultValue;
            }
            catch (Exception ex)
            {
                DelegateAndEvent.Instance.AddAlarmInfo($"获取系统配置{configKey}失败 {ex.Message}");
                return defaultValue;
            }
        }
        #endregion
    }
}
